//
//  MineEditUserInfoViewController.m
//  UniversalApp
//
//  Created by 志刚杨 on 2018/1/31.
//  Copyright © 2018年 voidcat. All rights reserved.
//

#import "MineEditUserInfoViewController.h"
#import "EditHeaderImgeTableViewCell.h"
#import "CYImagePickerViewController.h"
#import "EditUserNickname.h"
#import "EditSexTableViewCell.h"
#import "EditUserModel.h"
#import "EditPhotoTableViewCell.h"
#import "CYImageHeader.h"
@interface MineEditUserInfoViewController ()<QMUITableViewDelegate,QMUITableViewDataSource,TZImagePickerControllerDelegate>
@property(nonatomic, strong) NSMutableArray *dataSource;
@property(nonatomic, strong) NSString *eidtNickname;

@property(nonatomic, strong) UIImage *headerImage;//头像图片
@property(nonatomic, strong) NSMutableArray *photoArray;//用户选择的图片
@property(nonatomic, strong) NSMutableArray *deleteImage;//删除的图片

@property(nonatomic, assign) int urlImageCount;//记录真实图片的数量
@end

@implementation MineEditUserInfoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = ASLocalizedString(@"个人信息");
    [self initData];
    [self creatUI];
    [self.tableView reloadData];
}

-(void)initData
{
    _dataSource = [NSMutableArray arrayWithObjects:ASLocalizedString(@"头像"),ASLocalizedString(@"昵称"),ASLocalizedString(@"性别"), nil];
    _deleteImage = [NSMutableArray array];
    _photoArray = [NSMutableArray array];
    _urlImageCount = curUser.img.count;
}

-(void)creatUI
{
    //注册cell
    [self.tableView registerNib:[UINib nibWithNibName:[EditHeaderImgeTableViewCell className] bundle:nil] forCellReuseIdentifier:[EditHeaderImgeTableViewCell className]];
    
    [self.tableView registerNib:[UINib nibWithNibName:[EditUserNickname className] bundle:nil] forCellReuseIdentifier:[EditUserNickname className]];

    //性别
    [self.tableView registerNib:[UINib nibWithNibName:[EditSexTableViewCell className] bundle:nil] forCellReuseIdentifier:[EditSexTableViewCell className]];
    
    //图片列表
    [self.tableView registerNib:[UINib nibWithNibName:[EditPhotoTableViewCell className] bundle:nil] forCellReuseIdentifier:[EditPhotoTableViewCell className]];
    
    
    self.tableView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - kNavBarHeight);
    self.tableView.mj_header.hidden = YES;
    self.tableView.mj_footer.hidden = YES;
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    [self.view addSubview:self.tableView];
    
    
    //添加保存按钮

    [self addNavigationItemWithTitles:@[ASLocalizedString(@"保存   ")] isLeft:NO target:self action:@selector(navClick:) tags:@[@100]];
}

-(void)viewWillAppear:(BOOL)animated
{
    
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if(section == 0)
    {
        return _dataSource.count;
    }
    else
    {
        return 1;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if(indexPath.section == 0)
    {
        return 48;
    }
    else
    {
        NSLog(@"height:=====%f",CY_IMAGE_HEIGHT);
        return CY_IMAGE_BG_HEIGHT;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if(indexPath.section == 0)
    {
        NSString *cellname = [_dataSource objectAtIndex:indexPath.row];
        if([cellname containsString:ASLocalizedString(@"头像")])
        {
            EditHeaderImgeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:[EditHeaderImgeTableViewCell className] forIndexPath:indexPath];
            [cell setHeaderImage:_headerImage];
            return cell;
        }
        else if([cellname containsString:ASLocalizedString(@"昵称")])
        {
            
            EditUserNickname *cell = [tableView dequeueReusableCellWithIdentifier:[EditUserNickname className] forIndexPath:indexPath];
            
            cell.userDidChange = ^(NSString *text) {
                _eidtNickname = text;
                NSLog(ASLocalizedString(@"昵称%@"),text);
            };
            
            return cell;

        }
        else/* if([cellname isEqualToString:ASLocalizedString(@"性别")])*/
        {
            EditSexTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:[EditSexTableViewCell className] forIndexPath:indexPath];            
            return cell;
            
        }
    }
    else
    {
        EditPhotoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:[EditPhotoTableViewCell className] forIndexPath:indexPath];
        [cell.addimage removeAllImage];
        [cell addImage:curUser.img];
        int i=0;
        for (NSDictionary *image in curUser.img) {
            if([[image valueForKey:@"status"] intValue] == 1)
            {
                [cell.addimage removieAuditingIndex:i];
            }
            else
            {
                
            }
            
            i++;
        }
        NSLog(@"imagecell%@",curUser.img);
        @weakify(self);
        @weakify(cell);
        
        //添加图片
        cell.addClickBlock = ^{
            [weak_self selelctCoverWithCell:weak_cell];
        };
        
        //删除图片
        cell.deleClickBlock = ^(NSString *type, NSString *imgid,int index) {
            //type 1 为网络下载的图片 type2本地新增的图片 type3 添加按钮
            if([type isEqualToString:@"1"] && ![imgid isEqualToString:@"0"])
            {
                _urlImageCount --;
                [self willDeleteWithID:imgid];
            }
            else
            {
                //新添加的图片应当是索引值（index）减去网络图片后的
                int delindex = cell.addimage.imagearr.count - _urlImageCount -index - 1;//这里减一是为了给数组用，数组是从0开始的
                [_photoArray removeObjectAtIndex:delindex];
                NSLog(@"%d",delindex);
            }
        };
        return cell;
        
    }

}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 20;
}

//返回每组头部view
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    UIView *headerView = [[UIView alloc]init];
    
    headerView.backgroundColor = [UIColor groupTableViewBackgroundColor];
    
    UILabel *label = [[UILabel alloc]init];
    
    label.textColor = [UIColor grayColor];
    
    label.font = [UIFont systemFontOfSize:13];
    
    label.frame = CGRectMake(15, 0, SCREEN_WIDTH, 20);
    
    [headerView addSubview:label];
    
    if (section == 0) {
        
        label.text = ASLocalizedString(@"个人信息");
        
    }else{
        
        label.text = ASLocalizedString(@"个人封面（真实丰富的照片有利于被更多人发现）");
        
    }
    
    return headerView;
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSString *cellname = [_dataSource objectAtIndex:indexPath.row];
    if([cellname isEqualToString:ASLocalizedString(@"头像")] && indexPath.section == 0)
    {
        [self selectPhoto];
    }
    
    if(indexPath.section == 1)
    {
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
    // Dispose of any resources that can be recreated.
}

-(void)selectPhoto
{
    CYImagePickerViewController *imagePickerVc = [[CYImagePickerViewController alloc] initWithMaxImagesCount:1 delegate:self];
    [imagePickerVc.navigationController.navigationBar setTintColor:[UIColor blackColor]];
    imagePickerVc.naviBgColor = [UIColor blackColor];
    // You can get the photos by block, the same as by delegate.
    // 你可以通过block或者代理，来得到用户选择的照片.
    [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        if(photos.count >0)
        {
            _headerImage = photos[0];
            [self.tableView reloadData];
        }
    }];
    imagePickerVc.naviTitleColor = [UIColor blackColor];
    imagePickerVc.barItemTextColor =  [UIColor blackColor];
    imagePickerVc.oKButtonTitleColorNormal = [UIColor blackColor];
    imagePickerVc.showSelectBtn = YES;
    [self presentViewController:imagePickerVc animated:YES completion:nil];
}

-(void)selelctCoverWithCell:(EditPhotoTableViewCell *)cell
{
    
    //当前图片可选的数量 = 6 - 网络图片 - 已选择的本地图片
    CYImagePickerViewController *imagePickerVc = [[CYImagePickerViewController alloc] initWithMaxImagesCount:6 - _urlImageCount - _photoArray.count delegate:self];
    [imagePickerVc.navigationController.navigationBar setTintColor:[UIColor blackColor]];
    imagePickerVc.naviBgColor = [UIColor blackColor];
    // You can get the photos by block, the same as by delegate.
    // 你可以通过block或者代理，来得到用户选择的照片.
    [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        if(photos.count >0)
        {
            [_photoArray addObjectsFromArray:photos];
            [cell addImage:photos];
        }
        
    }];
    imagePickerVc.naviTitleColor = [UIColor blackColor];
    imagePickerVc.barItemTextColor =  [UIColor blackColor];
    imagePickerVc.oKButtonTitleColorNormal = [UIColor blackColor];
    imagePickerVc.showSelectBtn = YES;
    [self presentViewController:imagePickerVc animated:YES completion:nil];
}

-(void)willDeleteWithID:(NSString *)imgid
{
    [[HUDHelper sharedInstance] syncLoading];
    NSString *url = [[CYURLUtils sharedCYURLUtils] makeURLWithC:@"user_api" A:@"del_image"];
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    [param setObject:imgid forKey:@"id"];
    
    [CYNET POSTv2:url parameters:param responseCache:^(id responseObject) {
        
    } success:^(id responseObject) {
        [[HUDHelper sharedInstance] syncStopLoading];
        [[[EditUserModel alloc] init] updateUserinfo:^(BOOL success) {
            [self.tableView reloadData];
        }];
        [[HUDHelper sharedInstance] tipMessage:ASLocalizedString(@"删除成功")];
    } failure:^(NSString *error) {
        [[HUDHelper sharedInstance] syncStopLoading];
        [MBProgressHUD showTopTipMessage:error];
    } hasCache:NO];
    
    [_deleteImage addObject:imgid];
}

#pragma mark - 导航点击
-(void)navClick:(UIButton *)button
{
    button.enabled = NO;
    EditUserModel *model = [EditUserModel new];
    
    [model saveUserNickName:_eidtNickname andHearimage:_headerImage AndPhoto:_photoArray AndDeletePhoto:_deleteImage :^(BOOL success) {
        button.enabled = YES;
        [self.navigationController popViewControllerAnimated:YES];
    }];

}



/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
